﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Framework.Exceptions.RepositoryExceptions;
using HelperTools;
using Interfaces.Criteria;
using Interfaces.Filters;
using Interfaces.Models;
using Interfaces.Providers;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.EconomicInformationModels;

namespace SQLRepositories.EconomicRepositories
{
    public class IndustryRepository : EntityBaseRepository<IndustryModel>, IIndustryRepository, IEconomicDataProvider<IEnumerable<IIndustry>, IIndustryFilter, IKeySupportedCriteria>
    {
        public IndustryRepository(IDBEconomicInformationServiceContext context) : base(context)
        {}

        public void Create(IndustryModel item)
        {
            Context.Industries.Add(item);
            Context.SaveChanges();
        }

        public IndustryModel GetById(Guid id)
        {
            return (from ind in Context.Industries
                    where ind.Id.Equals(id)
                    select ind)
                .FirstOrDefault();
        }

        public void Delete(Guid id)
        {
            var removedItem = GetById(id);
            if(removedItem == null)
                throw new EntityNotFoundException("Industry");
            Context.Industries.Remove(removedItem);
            Context.SaveChanges();
        }

        public void Delete(IndustryModel item)
        {
            Context.Industries.Remove(item);
            Context.SaveChanges();
        }

        public IEnumerable<IndustryModel> GetAll()
        {
            return Context.Industries;
        }


        public IEnumerable<IIndustry> GetData(IKeySupportedCriteria criteria, IIndustryFilter filter)
        {
            IEnumerable<IndustryModel> source = from ind in Context.Industries 
                                                where criteria.Identificators.Contains(ind.Key) 
                                                select ind;
            if (filter == null)
                throw new ArgumentNullException("filter");
            if (criteria == null)
                throw new ArgumentNullException("criteria");

            RepositoryMappingHelper.ResetMapping();
            RepositoryMappingHelper.CreateQuoteMapping();
            RepositoryMappingHelper.CreateCompanyMapping(criteria.IsFullLoading, filter
                                                         .With(x => x.CompanyFilter)
                                                         .With(x => x.QuoteisFilter));
            RepositoryMappingHelper.CreateIndustryMapping(criteria.IsFullLoading, filter
                                                         .With(x => x.CompanyFilter));

            var result = Mapper.Map<IEnumerable<IndustryModel>, IEnumerable<IIndustry>>(source);
            return filter.Filtrate(result) as IEnumerable<IIndustry>;

        }
    }
}
